<?php

use Illuminate\Database\Capsule\Manager as DB;

#[业绩计算控制器]
class CalcController extends CoreController
{
    public function init()
    {
        if (!$this->isCli()) {
            throw new Exception("Go to cli please!", '303');
        }
        parent::init();
    }

    #[重组会员关系]
    public function memberChildrenAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->select('id', 'parent_member_id')
            ->orderBy('id', 'asc')
            ->chunk(100, function ($members) {
                foreach ($members as $member) {
                    if ($member->parent_member_id > 0) {
                        $parent = DB::table('member')->select('id', 'parent_member_id')->find($member->parent_member_id);
                        if (!$parent) {
                            continue;
                        }
                        $this->buildChildren($member, $parent, 1);
                    }
                }
            });
    }

    private function buildChildren($member, $parent, $level = 1)
    {
        $childRow = [
            'member_id' => $parent->id,
            'level' => $level,
            'children_id' => $member->id,
        ];
        DB::table('member_children')->insert($childRow);
        echo $childRow['children_id'], ' : ', $childRow['level'], ' : ', $childRow['member_id'], PHP_EOL;
        if ($parent->parent_member_id > 0) {
            $parent = DB::table('member')->select('id', 'parent_member_id')->find($parent->parent_member_id);
            if ($parent) {
                $this->buildChildren($member, $parent, ++$level);
            }

        }
    }

    #[重新计算个人业绩]
    public function reCalcTotalConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->whereIn('id', orderModel::query()->where('status', '>', 0)->selectRaw('if(customer_id>0, customer_id, member_id) as mem_id')->groupBy('mem_id')->pluck('mem_id'))
            // ->whereIn('id', membermergeModel::whereColumn('source_id', 'target_id')->pluck('target_id'))
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT count(*) as ttr from cs_order a where (a.customer_id=0 and a.member_id=:member_id or a.customer_id=:customer_id) and a.`status`>0 and a.id in (
                        SELECT order_id from cs_order_item b where b.member_id=:id and b.calc_consume=1 and b.refund_status<2)', ['member_id' => $member->id, 'customer_id' => $member->id, 'id' => $member->id]);
                    $ttr = $totaler[0]->ttr ?? 0;
                    $summer = DB::select('SELECT sum(pay_price) as smr FROM `cs_order` a inner join cs_order_item b on a.id=b.order_id where a.status>0 and b.calc_consume=1 and b.refund_status<2 and b.`member_id`=:id',
                        ['id' => $member->id]);
                    $smr = $summer[0]->smr ?? 0.00;

                    DB::table('member')->where('id', $member->id)->update(['total_consume_num' => $ttr, 'total_consume' => $smr]);
                    echo $member->id, ":", $ttr, ":", $smr, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算团队下个人业绩单数]
    public function reCalcTeamMemberConsumeAction()
    {
        $member_id = $this->get('member_id');
        memberchildrenModel::query()->where('member_id', $member_id)
            ->whereIn('children_id', orderModel::query()->where('status', '>', 0)->selectRaw('if(customer_id>0, customer_id, member_id) as mem_id')->groupBy('mem_id')->pluck('mem_id'))
            ->select('children_id as id')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT count(*) as ttr from cs_order a where (a.customer_id=0 and a.member_id=:member_id or a.customer_id=:customer_id) and a.`status`>0 and a.id in (
                        SELECT order_id from cs_order_item b where b.member_id=:id and b.calc_consume=1 and b.refund_status<2)', ['member_id' => $member->id, 'customer_id' => $member->id, 'id' => $member->id]);
                    $ttr = $totaler[0]->ttr ?? 0;
                    $summer = DB::select('SELECT sum(pay_price) as smr FROM `cs_order` a inner join cs_order_item b on a.id=b.order_id where a.status>0 and b.calc_consume=1 and b.refund_status<2 and b.`member_id`=:id',
                        ['id' => $member->id]);
                    $smr = $summer[0]->smr ?? 0.00;

                    DB::table('member')->where('id', $member->id)->update(['total_consume_num' => $ttr, 'total_consume' => $smr]);
                    echo $member->id, ":", $ttr, ":", $smr, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算个人佣金]
    public function reCalcTotalIncomeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->where('level', '>', 1)
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $agent_cms  = DB::table('agent_reward')->where('agent_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $gudong_cms = DB::table('gudong_reward')->where('gudong_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $qudai_cms  = DB::table('qudai_reward')->where('qudai_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $tuike_cms  = DB::table('tuike_reward')->where('tuike_id', $member->id)->where('status', '>=', 0)->sum('commission');
                    $smr = $agent_cms + $gudong_cms + $qudai_cms + $tuike_cms;
                    DB::table('member')->where('id', $member->id)->update(['total_income' => $smr]);

                    echo $member->id, ":", $smr, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算直推业绩]
    public function reCalcDirectConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->whereNull('deleted_at')
            ->select('id')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    if(DB::table('member')->where('parent_member_id', $member->id)->exists()) {
                        $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where deleted_at is null and parent_member_id=:id',
                            ['id' => $member->id]);
                        $tns     = $totaler[0]->tns ?? 0;
                        $summer  = DB::select('SELECT sum(total_consume) as cns from cs_member where deleted_at is null and parent_member_id=:id',
                            ['id' => $member->id]);
                        $cns     = $summer[0]->cns ?? 0.00;
                        DB::table('member')->where('id', $member->id)->update(['direct_consume_num' => $tns, 'direct_consume' => $cns]);
                    }else{
                        $tns     = 0;
                        $cns     = 0.00;
                        DB::table('member')->where('id', $member->id)->update(['direct_consume_num' => 0, 'direct_consume' => 0]);
                    }
                    echo $member->id, ':', $tns, ':', $cns, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算团队业绩]
    public function reCalcTeamConsumeAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            // ->where('level', '<=', 1)
            ->whereNull('deleted_at')
            ->select('id', 'team_consume', 'team_consume_num')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $myMem   = memberModel::query()->select('id', 'total_consume', 'total_consume_num', 'team_consume', 'team_consume_num', 'team_consume_old')->find($member->id);
                    $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where id=:id or (deleted_at is null and id in (SELECT children_id from cs_member_children where `member_id`=:member_id))',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $tns    = $totaler[0]->tns ?? 0;

                    $summer = DB::select('SELECT sum(total_consume) as cns from cs_member where id=:id or (deleted_at is null and id in (SELECT children_id from cs_member_children where `member_id`=:member_id))',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $cns    = $summer[0]->cns ?? 0.00;
                    $cns    += $myMem->team_consume_old ?? 0.00;
                    $adjust = DB::table('member_teamconsume_adjust_log')->where('member_id', $member->id)->sum('adjust');
                    $cns    += $adjust ?? 0.00;

//                    if ($member->team_consume_num != $tns) {
//                        $myMem->team_consume_num = $tns;
//                    }
//                    if ($member->team_consume != $cns) {
//                        $myMem->team_consume = $cns;
//                    }
//                    $myMem->save();

                    echo $member->id, ' : ', $cns, ' : ' , $tns,  PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[重新计算团队业绩单数]
    public function reCalcTeamConsumeNumAction()
    {
        $start_on = $this->get('start_on', 0);
        $end_on = $this->get('end_on', 0);
        DB::table('member')
            ->where('id', '>', $start_on)
            ->where('id', '<=', $end_on)
            ->select('id', 'team_consume_num')
            ->orderBy('id', 'asc')
            ->chunk(200, function ($members) {
                foreach ($members as $member) {
                    $totaler = DB::select('SELECT sum(total_consume_num) as tns from cs_member where id=:id or id in (SELECT children_id from cs_member_children where `member_id`=:member_id)',
                        ['id' => $member->id, 'member_id' => $member->id]);
                    $tns = $totaler[0]->tns;
                    DB::table('member')->where('id', $member->id)->update(['team_consume_num' => $tns]);
                    echo $member->id, ':', $tns, PHP_EOL;
                }
            });
        echo 'Done', PHP_EOL;
    }

    #[更新合并账号后的团队业绩]
    public function reCalcMergedTeamConsumeAction()
    {
        $merged = membermergeModel::query()->where('created_at', '<', '2022-05-26 15:00:00')->select('id', 'source_id', 'target_id')->get();
        foreach ($merged as $oneMerge){
            // 8. 加新上线所有人的团队业绩
            $source = \memberModel::withTrashed()->where('id', $oneMerge->source_id)->select('team_consume', 'team_consume_num')->first();
            if($source && $source->team_consume>0) {
                $newParents = \memberchildrenModel::query()->where('children_id', $oneMerge->target_id)->pluck('member_id');
                \memberModel::query()->whereIn('id', $newParents)->increment('team_consume', $source->team_consume);
                \memberModel::query()->whereIn('id', $newParents)->increment('team_consume_num', $source->team_consume_num);
            }
            echo $oneMerge->id. ': target_id', $oneMerge->target_id, ' - 上级业绩已更新', PHP_EOL;
        }

        echo 'Done', PHP_EOL;
    }

    #[找到所有的团队订单]
    public function fetchAllTeamOrderAction()
    {
        $id           = 2088;
        $query    = (new \orderModel)->withTrashed()->with('member')->where('status', '>', 0);
        $query    = $query->where(function ($query) use ($id) {
            $query->whereRaw("customer_id in (SELECT children_id from cs_member_children where `member_id`={$id})")
                ->orWhere(function ($query) use ($id) {
                    $query->where('customer_id', 0)
                        ->whereRaw("member_id in (SELECT children_id from cs_member_children where `member_id`={$id})");
                })->orWhere('customer_id', $id)
                ->orWhere(function ($query) use ($id) {
                    $query->where('customer_id', 0)
                        ->where('member_id', $id);
                });
        });
        $query    = $query->whereExists(function ($query) {
            $query->from('order_item')->whereColumn('order_item.order_id', 'order.id')
                ->where('calc_consume', '=', 1)
                ->where('refund_status', '<', 2);
        });
        $rows = $query->pluck('id')->toJson();
        echo $rows;
    }
    
    #[判断任务有无完成]
    public function renwujudgeAction()
    {
        $taskMems = taskmemberModel::query()
            ->where('task_expired_at', '>=', date('Y-m-d H:i:s'))
            ->where('task_status', 0)
            ->get();
        $levels = agentlevelModel::get();
        foreach($taskMems as $taskMem) {
            if( $this->isMatchDowngradeLevelRule($taskMem) ){

                $mem = memberModel::query()->where('id', $taskMem->member_id)->first();
                $team_child_agent_all_counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where `member_id`=:id) ', ['id' => $mem->id]);
                $team_child_agent_direct_counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where level=1 and `member_id`=:id) ', ['id' => $mem->id]);
                $team_child_agent = [];
                foreach ($levels as $level) {
                    $counter = DB::select('SELECT count(*) as cnt from cs_member where level=:level and id in (SELECT children_id from cs_member_children where `member_id`=:id) ',
                        ['level' => $level->level,
                            'id'    => $mem->id]);
                    $cnt     = $counter[0]->cnt;
                    array_push($team_child_agent,  [
                        'level' => $level->level,
                        'name'  => $level->name,
                        'count' => $cnt
                    ]);
                }
                $status = [
                    'team_consume'  =>  $mem->team_consume,
                    'total_consume' =>  $mem->total_consume,
                    'team_child'    =>  memberchildrenModel::query()->where('member_id', $mem->id)->count(),
                    'team_child_direct'=>   memberchildrenModel::query()->where('member_id', $mem->id)->where('level', 1)->count(),
                    'team_child_agent_all'  => $team_child_agent_all_counter[0]->cnt,
                    'team_child_agent_direct'=>$team_child_agent_direct_counter[0]->cnt,
                    'team_child_agent'=> $team_child_agent,
                ];
                $awards = [];
                $reward_rules  = json_decode($taskMem->reward_rules, true);
                foreach ($reward_rules as $reward_rule) {
                    if($reward_rule['level']==$mem->level){
                        foreach($reward_rule['awards'] as $award) {
                            if($award['num']>0){
                                $awards[] = $award;
                            }
                        }
                    }
                }
                //任务完成
                $taskMem->after_member_status = json_encode($status, JSON_UNESCAPED_UNICODE);
                $taskMem->task_status = 1;
                $taskMem->reward_status = 1;
                $taskMem->reward_expired_at = date('Y-m-d H:i:s', strtotime("+{$taskMem->reward_duration} day"));
                $taskMem->reward_result = json_encode($awards, JSON_UNESCAPED_UNICODE);
                $taskMem->updated_at = date('Y-m-d H:i:s');
                $taskMem->save();
            }
        }
    }

    public function isMatchDowngradeLevelRule($taskMem)
    {
        $member = memberModel::query()->find($taskMem->member_id);
        $rawStatus = json_decode($taskMem->before_member_status, true);
        $finish_rules = json_decode($taskMem->finish_rules, true);
        $upgrade_type = true; // 升级类型, true为所有条件全部满足  false为满足任一条件即可升级
        if (!empty($finish_rules)) {
            foreach ($finish_rules as $name => $value) {
                if (isset($value['flag']) && $value['flag'] == 1) {
                    switch ($name) {
                        case 'team_consume':            // 团队业绩
                            if ($member->team_consume - $rawStatus['team_consume'] < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                        case 'total_consume':           // 自购订单金额
                            if ($member->total_consume - $rawStatus['total_consume']  < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                        case 'team_child':              // 团队人数
                            if (DB::table('member_children')->where('member_id', $member->id)->count() - $rawStatus['team_child']  < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                        case 'team_child_direct':       // 直推人数
                            if (DB::table('member_children')->where('member_id', $member->id)->where('level', 1)->count() - $rawStatus['team_child_direct']  < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                        case 'team_child_agent_all':    // 代理商人数
                            $counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where `member_id`=:id) ', ['id' => $member->id]);
                            $cnt     = $counter[0]->cnt;
                            if ($cnt - $rawStatus['team_child_agent_all'] < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                        case 'team_child_agent_direct': // 直推代理商人数
                            $counter = DB::select('SELECT count(*) as cnt from cs_member where level>1 and id in (SELECT children_id from cs_member_children where level=1 and `member_id`=:id) ', ['id' => $member->id]);
                            $cnt     = $counter[0]->cnt;
                            if ($cnt - $rawStatus['team_child_agent_direct']  < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                            break;
                    }
                } elseif ($name == 'team_child_agent') { // 各等级代理会员人数
                    foreach ($value as $child_agent) {
                        if ($child_agent['flag'] == 1) {
                            $counter = DB::select('SELECT count(*) as cnt from cs_member where level=:level and id in (SELECT children_id from cs_member_children where `member_id`=:id) ',
                                ['level' => $child_agent['level'],
                                    'id'    => $member->id]);
                            $cnt     = $counter[0]->cnt;

                            $rawCnt  = 0;
                            foreach ($rawStatus['team_child_agent'] as $onelevel){
                                if($onelevel->level==$child_agent['level']){
                                    $rawCnt = $onelevel->count;
                                }
                            }

                            if ($cnt - $rawCnt < $value['amount']) {
                                return false;
                            } elseif (!$upgrade_type) {
                                return true;
                            }
                        }
                    }
                }
            }
            // 循环完所有, 能跑到这里, 说明所有的条件已全部符合
        }

        // 未设置任何条件, 可为默认等级
        return true;
    }

}
